<?php
/**
* 数据库操作模块 工具类
*
* 数据库操作模块 工具类的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Tool\DataBase;

use Illuminate\Support\Facades\DB;

class SQL{

    //判断数据是否存在(s)
    static function count($input){
        $count  = DB::table($input['table'])
                  ->where($input['where'])
                  ->count();
        return $count;
    }


    //数据修改
    static function update($input){
        $upd    = DB::table($input['table'])
                  ->where($input['where'])
                  ->update($input['update']);
        return $upd;
    }

    //获取数据
    static function first($input){
        $first  = DB::table($input['table'])
                  ->where($input['where'])
                  ->first();
        return $first;
    }

    //获取字段
    static function pluck($input){
        $pluck  = DB::table($input['table'])
                  ->where($input['where'])
                  ->value($input['pluck']);
        return $pluck;
    }

    //添加数据
    static function insert($input){
        $insert = DB::table($input['table'])
                  ->insertGetId($input['insert']);
        return $insert;
    }

    //获得某字段
    static function lists($input){
        $lists  = DB::table($input['table'])
                  ->where($input['where'])
                  ->pluck($input['lists'])
                  ->toArray();
        return $lists;
    }

    //获取所有数据
    static function get($input){
        $input['order'] = isset($input['order'])?$input['order']:'created_at';
        $input['sort'] = isset($input['sort'])&&$input['sort']=='desc'?'desc':'asc';
        $get    = DB::table($input['table'])
                  ->where($input['where'])
                  ->orderBy($input['order'],$input['sort'])
                  ->get()
                  ->toArray();
        return $get;
    }

    //分页
    static function paginate($input){
        $input['order'] = isset($input['order'])?$input['order']:'created_at';
        $input['sort'] = isset($input['sort'])&&$input['sort']=='desc'?'desc':'asc';
        $pag    = DB::table($input['table'])
                  ->where($input['where'])
                  ->orderBy($input['order'],$input['sort'])
                  ->paginate($input['per_page']);
        return $pag;
    }

    static function CatchDo(){
        DB::rollback();
    }

    static function FinallyDo(){
        DB::commit();
    }

    static function FirstDo(){
        DB::beginTransaction();
    }

    static function test(){
        $order  = DB::table('orders')
                  ->get();
        $num    = 0;
        foreach($order as $or){
            $arr['table'] = 'order_details';
            $arr['where'] = array('order_id'=>$or->order_id);
            $arr['update']= array('create_id'=>$or->create_id);
            $num    += self::update($arr);
        }
        return $num;
    }
}
